import {getFormData} from "@/utils";
import {uploadPreview} from "@/api/news";
import {ref} from "vue";

export default () => {
    const rules = {
        title: [
            {
                required: true,
                message: '请输入新闻的标题',
                trigger: 'blur'
            },
        ],
        date: [
            {
                type: 'date',
                required: true,
                message: '请选择新闻的日期!',
                trigger: 'change',
            },
        ],
        desc: [
            {
                required: true,
                message: '请输入新闻的介绍',
                trigger: 'blur'
            },
        ],
        imgSrc: [
            {
                required: true,
                message: '请上传预览图!',
                trigger: 'change'
            }
        ],
        category: {
            required: true,
            message: '请选择新闻的分类!',
            trigger: 'change',
        }
    }
    const ruleForm = ref({
        imgSrc: '',
        title: '',
        desc: '',
        date: '',
        category: 'companyNews'
    })
    const selectOptions = [
        {
            label: '公司新闻',
            value: 'companyNews',
            id: 1
        },
        {
            label: '媒体报道',
            value: 'companyReport',
            id: 2,
        },
        {
            label: '集团公告',
            value: 'companyNotice',
            id: 3,
        }
    ]
    const initRuleForm = ({title, imgSrc, desc, date, category}) => {
        ruleForm.value = {
            title,
            imgSrc,
            desc,
            date,
            category,
        }
    }
    const uploadPreviewHandler = async (file) => {
        const formData = getFormData({
            preview: file
        })
        const {success, url} = await uploadPreview(formData)
        if (!success) {
            console.log('预览图上传不成功!');
            return
        }
        ruleForm.value.imgSrc = url
    }
    return {
        rules,
        ruleForm,
        uploadPreviewHandler,
        initRuleForm,
        selectOptions,
    }
}